package com.duck.duckchatbackend.websocket.netty;

import com.duck.duckchatbackend.entity.config.AppConfig;
import com.duck.duckchatbackend.utils.StringTools;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Component
@ChannelHandler.Sharable
public class NettyWebSocketStarter implements Runnable {
    private static final Logger logger = LoggerFactory.getLogger(NettyWebSocketStarter.class);
    //处理链接线程组
    private static EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    //处理读写线程组
    private static EventLoopGroup workerGroup = new NioEventLoopGroup();
    @Resource
    private HandlerWebSocket handlerWebSocket;

    @Resource
    private AppConfig appConfig;

    @PreDestroy
    public void close() {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }

    @Override
    public void run() {
        try {
            //创建并配置服务器引导类ServerBootstrap实例
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            // 设置服务器的BossGroup和WorkerGroup线程组
            // BossGroup用于接收客户端连接，WorkerGroup用于处理网络通信
            serverBootstrap.group(bossGroup, workerGroup);
            //指定通道
            serverBootstrap.channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.DEBUG)).childHandler(new ChannelInitializer() {
                        @Override
                        protected void initChannel(Channel channel) throws Exception {
                            ChannelPipeline pipeline = channel.pipeline();
                            // 设置几个重要的处理器
                            // 对http协议的支持，使用http的编码器，解码器
                            pipeline.addLast(new HttpServerCodec());
                            // 聚合解码器 httpRequest/httpContent/lastHttpContent到fullHttpRequest
                            // 保证接收的http请求完整
                            pipeline.addLast(new HttpObjectAggregator(64 * 1024));
                            // 心跳 long readerIdleTime, long writerIdleTime, long allIdleTime, TimeUnit unit
                            // readIdleTime, 读超时时间 即测试端一定时间内未接受到被测试端消息
                            // writeIdleTime, 写超时时间 即测试端一定时间内未向被测试端发送消息
                            pipeline.addLast(new IdleStateHandler(60, 0, 0, TimeUnit.SECONDS));
                            // 心跳处理器
                            pipeline.addLast(new HandlerHeartBeat());
                            //将http协议升级为ws协议，使其支持websocket;
                            pipeline.addLast(new WebSocketServerProtocolHandler("/ws", null, true, 64 * 1024, true, true, 10000L));
                            pipeline.addLast(handlerWebSocket);
                        }
                    });
            Integer wsPort = appConfig.getWsPort();
            String wsPortStr = System.getProperty("ws.port");
            if(!StringTools.isEmpty(wsPortStr)) {
                wsPort = Integer.parseInt(wsPortStr);
            }
            ChannelFuture channelFuture = serverBootstrap.bind(appConfig.getWsPort()).sync();
            logger.info("启动netty服务启动成功，端口：{}", appConfig.getWsPort());
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            logger.error("启动netty失败", e);
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
